package company.kuaishou;

/**
 * @author LiangMu
 * @version \$Id: Main.java, v 0.1, 2023年05月11日 18:40 LiangMu Exp $$
 */
public class Times {

    /**
     * 给定两个字符串组成的正整数，num1 和 num2，请计算两个数字的乘积【不准用BigDecimal工具类】
     */
    public static String times(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) return "0";
        char[] chars = num1.toCharArray();
        StringBuilder ans = new StringBuilder("0");
        int mark = 1;
        for (int i = chars.length - 1; i >= 0; i--) {
            StringBuilder builder = singleTimes(chars[i] - '0', num2, mark);
            ans = plus(ans, builder);
            mark *= 10;
        }
        return ans.toString();
    }

    public static StringBuilder singleTimes(int num1, String num2, int temp) {
        StringBuilder ans = new StringBuilder();
        char[] chars = num2.toCharArray();
        int mark = 0;
        for (int i = chars.length - 1; i >= 0; i--) {
            int sum = (chars[i] - '0') * num1 + mark;
            mark = sum / 10;
            ans.append(sum % 10);
        }
        if (mark > 0) ans.append(mark);
        ans.reverse();
        while (temp > 1) {
            ans.append(0);
            temp /= 10;
        }
        return ans;
    }

    public static StringBuilder plus(StringBuilder num1, StringBuilder num2) {
        if (num1.toString().equals("0")) return num2;
        if (num2.toString().equals("0")) return num1;
        char[] chars1 = num1.toString().toCharArray();
        char[] chars2 = num2.toString().toCharArray();
        int mark = 0;
        int len1 = chars1.length;
        int len2 = chars2.length;
        int len = Math.max(len1, len2);
        StringBuilder ans = new StringBuilder();
        for (int i = 1; i <= len; i++) {
            int n1 = len1 >= i ? chars1[len1 - i] - '0' : 0;
            int n2 = len2 >= i ? chars2[len2 - i] - '0' : 0;
            int sum = n1 + n2 + mark;
            mark = sum >= 10 ? 1 : 0;
            ans.append(sum % 10);
        }
        if (mark > 0) ans.append(mark);
        return ans.reverse();
    }

    public static void main(String[] args) {
        String str1 = "123";
        String str2 = "456";
        System.out.println(times(str1, str2));
    }
}
